<?php
/**
 * Created by PhpStorm.
 * User: LiuZongqi
 * Date: 2021/1/14
 * Time: 14:32
 */

namespace app\admin\controller;

use app\admin\common\Base;

class System extends Base {
    public function index(){
        $info = db('system_config')->field('code,val')->select();
        $system = [];
        foreach ($info as $v){
            $system[$v['code']] = $v['val'];
        }
        $this->assign('info',$system);
        return $this->fetch();
    }

    public function edit(){
        if ($this->request->isPost()){
        	$data = input('post.');
        	$data['login_captcha'] = !empty($data['open_captcha']) ? 1 : 0;
//        	$data['msg_time'] = $data['msg_time'] ? $data['msg_time'] : 3000;
            $data['inquiry_send_email'] = !empty($data['inquiry_send_email']) ? 1 : 0;
            $data['forbidden'] = !empty($data['forbidden']) ? 1 : 0;
        	unset($data['open_captcha']);
        	//启动事务
			db()->startTrans();
			try{
				foreach ($data as $k => $v){
					db('system_config')->where('code',$k)->update(['val'=>$v]);
				}
				insert_system_log('修改系统设置','');
				db()->commit();
				$json = ['code'=>'suc','msg'=>'修改成功'];
			}catch (\Exception $e){

				db()->rollback();
				$json = ['code'=>'err','msg'=>'修改成功'];
			}
			return json($json);
		}
    }

    public function log($page=1,$limit=10,$start_time='',$end_time='',$keyword=''){
        if (request()->isPost()){

            $where = [];
            if (session('u_id') !== 1){
                $where[] = ['user','<>',1];
            }
            if (!empty($keyword)){
                $where[] = ['name|content','like','%'.$keyword.'%'];
            }
            if (!empty($start_time)){
                $start_time = strtotime($start_time);
                $end_time = strtotime($end_time);
                $where[] = ['create_time','between',[$start_time,$end_time]];
            }

            $count = db('system_log')->where($where)->count();
            $list = db('system_log')
                    ->where($where)
                    ->order('id','desc')
                    ->page($page,$limit)
                    ->select();
            foreach ($list as $k => $v){
                $list[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
            return json(['code' => 'suc', 'msg' => '请求数据成功', 'count' => $count, 'data' => $list]);
        }

        return $this->fetch();
    }
}